Jest - mock read-only data


Posted by tsungtingdu on 2021-07-16

情境:在使用 @ViewChild 引入其他 component

@ViewChild(ChildComponent) childComponent: ChildComponent;

然後進行測試的情況下,需要 mock 這個 ChildComponent。

但是如果想要 mock 那些 read-only 的 attributes 的話,可以用 Object.defineProperty 來處理:

component.childComponent = {} as any;
Object.defineProperty(component.childComponent, 'isChild', { value: true });

當然這個方法也可以用在 mock 其他的 class, object 上


#Angular #Jest







Related Posts

 [10] 型別 - 內建型別、基本型別值

[10] 型別 - 內建型別、基本型別值

[07] JavaScript 入門 - 函式、即刻調用的函式運算式、閉包

[07] JavaScript 入門 - 函式、即刻調用的函式運算式、閉包

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 目錄結構

[ Nuxt.js 2.x 系列文章 ] Nuxt.js 目錄結構


Comments